<template>
	<view class="container-info">
		<view class="title" @click="returnCertificate">
			<view class="icon"></view>
			<view class="text">历史申请进度查询</view>
		</view>
		<view class="content-info">
			<view class="content-title">
				<view class="line"></view>
				<span class="title-info">请填写以下信息</span>
			</view>
			<view class="info">
				<view class="title-info">
					手机号
				</view>
				<up-input
				  class="option"
				  border="bottom"
				  v-model="telephoneNum"
				  clearable
				  placeholder="请输入手机号"
				  @blur="validatePhone"
				></up-input>
			</view>
			<view v-if="showError" class="error-message">
			  {{ errorText }}
			</view>
			<view class="content-title">
				<view class="line"></view>
				<span class="title-info">请选择历史申请类型</span>
			</view>
			<up-radio-group
			    class="selectOption"
			    v-model="radiovalue1"
			    placement="column"
			    @change="groupChange"
			  >
			    <up-radio
			      :customStyle="{marginBottom: '8px'}"
			      v-for="(item, index) in radiolist1"
			      :key="index"
			      :label="item.name"
			      :name="item.name"
			      @change="radioChange"
			    >
			    </up-radio>
			</up-radio-group>
			<up-button class="confirm" type="primary" text="查询" @click="queryInfo"></up-button>
		</view>
	</view>
	<up-popup class="pop-up-window" :show="isShowApply" mode="center" :round="10">
		<view class="application-history">
		    <view class="table-container">
		      <view class="table-header">
		        <text class="header-item">申请用途</text>
		        <text class="header-item">审核状态</text>
		        <text class="header-item">批复</text>
		      </view>
		      <scroll-view class="table-body" scroll-y="true">
		        <view 
		          v-for="(item, index) in tableData" 
		          :key="index" 
		          class="table-row"
		        >
		          <text class="table-cell">{{ item.appPurpose }}</text>
		          <text class="table-cell">{{ item.auditStatus }}</text>
		          <text class="table-cell">{{ item.auditDesc }}</text>
		        </view>
		      </scroll-view>
		    </view>
		</view>
		<view class="applyQuantity">
			您共有{{tableData.length}}条申请记录
		</view>
		<view class="button">
			<up-button type="primary" class="closeStyle" text="关闭" @click="closeFile"></up-button>
			<up-button type="primary" class="downloadStyle" text="下载证明" @click="downloadFile"></up-button>
		</view>
	</up-popup>
	<!-- 下载弹窗 -->
	<uni-popup ref="downloadPopup" type="bottom">
	  <view style="background: white; border-top-left-radius: 20px; border-top-right-radius: 20px; padding: 20px; max-height: 60vh;">
		<view style="text-align: center; padding-bottom: 15px; border-bottom: 1px solid #eee; margin-bottom: 15px;">
		  <text style="font-size: 18px; font-weight: bold;">附件下载</text>
		</view>
		
		<scroll-view style="max-height: 40vh;" scroll-y>
		  <view 
			v-for="(url, index) in applyInfoUrls" 
			:key="index"
			style="padding: 15px; border-bottom: 1px solid #f0f0f0; display: flex; align-items: center; justify-content: space-between;"
		  >
			<text @click="forceDownload(url)" style="color: #007aff; text-decoration: underline; flex: 1; margin-right: 10px; cursor: pointer;">
			  {{ getFileName(url) }}
			</text>
			<button @click="previewFile(url)" size="mini" type="primary">预览</button>
		  </view>
		</scroll-view>
		
		<view style="text-align: center; padding-top: 15px;">
		  <button @click="closeDownloadPopup" size="mini" type="default">关闭</button>
		</view>
	  </view>
	</uni-popup>
	
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
// 返回气象证明申请模块
const returnCertificate =()=>{
	uni.navigateTo({
	  url: '/pages/applicationCertificate/applicationCertificate'
	});
}
// 填写手机号
const telephoneNum = ref('')
const showError = ref(false)
const errorText = ref('请输入正确的手机号码')

const validatePhone = () => {
  // 更完善的手机号正则验证
  const phoneReg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
  
  if (!telephoneNum.value.trim()) {
    showError.value = true
    errorText.value = '请输入手机号码'
    return false
  } else if (!phoneReg.test(telephoneNum.value)) {
    showError.value = true
    errorText.value = '请输入正确的手机号码'
    return false
  } else {
    showError.value = false
    return true
  }
}

// 监听输入变化，实时验证
watch(telephoneNum, (newVal) => {
  if (showError.value) {
    validatePhone()
  }
})
// 单选框(个人查询or单位查询)
// 基本案列数据
const radiolist1 = reactive([
  {
    name: '个人申请查询',
    disabled: false,
  },
  {
    name: '单位申请查询',
    disabled: false,
  },
]);

// up-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
const radiovalue1 = ref('个人申请查询');

const groupChange = (n) => {
  console.log('groupChange', n);
};

const radioChange = (n) => {
  console.log('radioChange', n);
};

//查询
const queryInfo = async ()=>{
  // 判断手机号是否合理，若不合理则退出
  if(!validatePhone()){
	  uni.showToast({
	    title: '请输入正确的手机号', // 提示内容
	    icon: 'none', // 图标，可选值: success, loading, none
	    duration: 2000, // 显示时长(ms)，默认1500
	    position: 'center' // 位置，可选值: top, center, bottom
	  });
	  return
  }
  console.log('手机号验证通过:', telephoneNum.value)
  //清空申请列表数据
  tableData.value = [];
  //判断申请类型并查询
  if(radiovalue1.value=="个人申请查询"){
	  // 个人申请查询
	  await uni.request({
	    url: 'http://218.28.7.243:32201/api/wcertificate/wcList', // 请求URL
	    method: 'GET',
	    header: {
	      'Access-Control-Allow-Origin': '*',
	    },
	    data: {
	      wxId: telephoneNum.value
	    },
	    success: (res) => {
	      console.log('请求成功:', res);
		  // 申请记录数量
		  const applyLength = res.data.data.length
	  	  if(applyLength==0){
			uni.showToast({
			  title: '没有申请记录', // 提示内容
			  icon: 'none', // 图标，可选值: success, loading, none
			  duration: 2000, // 显示时长(ms)，默认1500
			  position: 'center' // 位置，可选值: top, center, bottom
			});
			return
	  	  }
		  console.log('zzz')
		  // 申请记录
		  const applyRecords = res.data.data
		  for(let i=0; i<applyRecords.length; i++){
			  console.log(applyRecords[i].appPurpose) // 申请用途
			  console.log(applyRecords[i].auditDesc) //批复
			  console.log(applyRecords[i].auditStatus) // 申请状态
			  //判断审核状态
			  if(applyRecords[i].auditStatus==0){
				  applyRecords[i].auditStatus='待审核'
			  }else if(applyRecords[i].auditStatus==1){
				  applyRecords[i].auditStatus='通过'
			  }else{
				  applyRecords[i].auditStatus='驳回'
			  }
			  let res = {
				  appPurpose:applyRecords[i].appPurpose,
				  auditDesc:applyRecords[i].auditDesc,
				  auditStatus:applyRecords[i].auditStatus
			  }
			  tableData.value.push(res)
		  }
		  console.log(tableData.value)
	  	  // 审核状态
	  	  let auditStatus = res.data.data[0].auditStatus
	  	  if(auditStatus==0){
	  		  uni.showToast({
	  		    title: '待审核', // 提示内容
	  		    icon: 'none', // 图标，可选值: success, loading, none
	  		    duration: 2000, // 显示时长(ms)，默认1500
	  		    position: 'center' // 位置，可选值: top, center, bottom
	  		  });
	  	  }else if(auditStatus==1){
	  		  uni.showToast({
	  		    title: '通过', // 提示内容
	  		    icon: 'success', // 图标，可选值: success, loading, none
	  		    duration: 2000, // 显示时长(ms)，默认1500
	  		    position: 'center' // 位置，可选值: top, center, bottom
	  		  });
			  // // 打开申请成功弹出框
			  // isShowApply.value = true
	  	  }else if(auditStatus==2){
	  		  uni.showToast({
	  		    title: '驳回:'+res.data.data[0].auditDesc, // 提示内容
	  		    icon: 'none', // 图标，可选值: success, loading, none
	  		    duration: 2000, // 显示时长(ms)，默认1500
	  		    position: 'center' // 位置，可选值: top, center, bottom
	  		  });
	  	  }
	  	  // 展示下载页面
	  	  isShowApply.value = true
	    },
	    fail: (err) => {
	      console.error('请求失败:', err);
	    },
	    complete: () => {
	      console.log('请求完成');
	    }
	  });	
  }else{
	  //单位申请查询
	  await uni.request({
	    url: 'http://218.28.7.243:32201/api/wcertificate/orgWcList', // 请求URL
	    method: 'GET',
	    header: {
	      'Access-Control-Allow-Origin': '*',
	    },
	    data: {
	      wxId: telephoneNum.value
	    },
	    success: (res) => {
	      console.log('请求成功:', res);
		  if(res.data.data.length==0){
			  uni.showToast({
				title: '没有申请记录', // 提示内容
				icon: 'none', // 图标，可选值: success, loading, none
				duration: 2000, // 显示时长(ms)，默认1500
				position: 'center' // 位置，可选值: top, center, bottom
			  });
			  return
		  }
		  
		  // 申请记录
		  const applyRecords = res.data.data
		  for(let i=0; i<applyRecords.length; i++){
			  console.log(applyRecords[i].appPurpose) // 申请用途
			  console.log(applyRecords[i].auditDesc) //批复
			  console.log(applyRecords[i].auditStatus) // 申请状态
			  //判断审核状态
			  if(applyRecords[i].auditStatus==0){
			  				  applyRecords[i].auditStatus='待审核'
			  }else if(applyRecords[i].auditStatus==1){
			  				  applyRecords[i].auditStatus='通过'
			  }else{
			  				  applyRecords[i].auditStatus='驳回'
			  }
			  let res = {
				  appPurpose:applyRecords[i].appPurpose,
				  auditDesc:applyRecords[i].auditDesc,
				  auditStatus:applyRecords[i].auditStatus
			  }
			  tableData.value.push(res)
		  }
		  
		  console.log('tableData',tableData.value)
		  
		  // 审核状态
		  let auditStatus = res.data.data[0].auditStatus
		  if(auditStatus==0){
			  uni.showToast({
				title: '待审核', // 提示内容
				icon: 'none', // 图标，可选值: success, loading, none
				duration: 2000, // 显示时长(ms)，默认1500
				position: 'center' // 位置，可选值: top, center, bottom
			  });
		  }else if(auditStatus==1){
			  uni.showToast({
				title: '通过', // 提示内容
				icon: 'success', // 图标，可选值: success, loading, none
				duration: 2000, // 显示时长(ms)，默认1500
				position: 'center' // 位置，可选值: top, center, bottom
			  });
		  }else if(auditStatus==2){
			  uni.showToast({
				title: '驳回:'+res.data.data[0].auditDesc, // 提示内容
				icon: 'none', // 图标，可选值: success, loading, none
				duration: 2000, // 显示时长(ms)，默认1500
				position: 'center' // 位置，可选值: top, center, bottom
			  });
		  }
		  // 展示下载页面
		  isShowApply.value = true
	    },
	    fail: (err) => {
	      console.error('请求失败:', err);
	    },
	    complete: () => {
	      console.log('请求完成');
	    }
	  });	
	  
  }
  console.log('执行到这了')
}
// 申请结果列表
const tableData = ref([])

// 下载文件模块
const isShowApply = ref(false)
// 保存气象证明文件地址
const applyInfoUrls = ref([])
// 查询气象证明文件
const downloadFile = async ()=>{
	//清空保存的气象证明文件地址
	applyInfoUrls.value=[]
	if(radiovalue1.value=="个人申请查询"){
		//查询下载链接
		await uni.request({
		  url: 'http://218.28.7.243:32201/api/wcertificate/wcList', // 请求URL
		  method: 'GET',
		  header: {
		    'Access-Control-Allow-Origin': '*',
		  },
		  data:{
			wxId: telephoneNum.value,
		  },
		  success: (res) => {
			if(res.data.code==200){
				const applyInfos = res.data.data
				for(let i=0;i<applyInfos.length;i++){
					// 把气象证明文件的地址保存
					applyInfoUrls.value.push(applyInfos[i].resFileUrl)
				}
				// 过滤掉空值、null和undefined
				applyInfoUrls.value = applyInfoUrls.value.filter(item => {
				  // 只有当item不是null、undefined且不为空值时才保留
				  return item !== null && item !== undefined && item !== '';
				});
				
				// 判断返回的长度
				if(applyInfoUrls.value.length==0){
					uni.showToast({
					  title: '无气象证明文件', // 提示内容
					  icon: 'none', // 图标，可选值: success, loading, none
					  duration: 2000, // 显示时长(ms)，默认1500
					  position: 'center' // 位置，可选值: top, center, bottom
					});
					return
				}
				
				console.log('111',applyInfoUrls.value)
				//展示弹窗
				showDownloadPopup()
				// 关闭弹窗
				isShowApply.value = false
				
			}
		  },
		  fail: (err) => {
		    console.error('请求失败:', err);
		  },
		  complete: () => {
		    console.log('请求完成11');
		  }
		});	
	}else{
		//查询下载链接
		await uni.request({
		  url: 'http://218.28.7.243:32201/api/wcertificate/orgWcList', // 请求URL
		  method: 'GET',
		  header: {
		    'Access-Control-Allow-Origin': '*',
		  },
		  data:{
			wxId: telephoneNum.value,
		  },
		  success: (res) => {
			console.log('res111',res)
			if(res.data.code==200){
				const applyInfos = res.data.data
				for(let i=0;i<applyInfos.length;i++){
					// 把气象证明文件的地址保存
					applyInfoUrls.value.push(applyInfos[i].resFileUrl)
				}
				// 过滤掉空值、null和undefined
				applyInfoUrls.value = applyInfoUrls.value.filter(item => {
				  // 只有当item不是null、undefined且不为空值时才保留
				  return item !== null && item !== undefined && item !== '';
				});
				// 判断返回的长度
				if(applyInfoUrls.value.length==0){
					uni.showToast({
					  title: '无气象证明文件', // 提示内容
					  icon: 'none', // 图标，可选值: success, loading, none
					  duration: 2000, // 显示时长(ms)，默认1500
					  position: 'center' // 位置，可选值: top, center, bottom
					});
					return
				}
				
				console.log('222',applyInfoUrls.value)
				//展示弹窗
				showDownloadPopup()
				// 关闭弹窗
				isShowApply.value = false
				
				
			}
		  },
		  fail: (err) => {
		    console.error('请求失败:', err);
		  },
		  complete: () => {
		    console.log('请求完成');
		  }
		});	
	}
	
}
// 关闭下载气象证明文件
const closeFile = ()=>{
	isShowApply.value = false
}  


// 下载弹窗
const downloadPopup = ref(null)

// 提取文件名
const getFileName = (url) => {
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    const fileName = pathname.substring(pathname.lastIndexOf('/') + 1)
    return decodeURIComponent(fileName)
  } catch (error) {
    return '下载文件'
  }
}

// 显示下载弹窗
const showDownloadPopup = () => {
  downloadPopup.value.open()
}

// 关闭下载弹窗
const closeDownloadPopup = () => {
  downloadPopup.value.close()
}

// 强制下载文件
const forceDownload = (url) => {
  const fileName = getFileName(url)
  
  //#ifdef H5
  // H5环境下使用fetch强制下载
  fetch(url)
    .then(response => response.blob())
    .then(blob => {
      const downloadUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(downloadUrl)
    })
    .catch(() => {
      // 如果fetch失败，回退到直接打开链接
      window.open(url, '_blank')
    })
  //#endif
  
  //#ifdef MP-WEIXIN
  // 微信小程序环境下提示用户复制链接或直接下载
  uni.downloadFile({
    url: url,
    success: (res) => {
      if (res.statusCode === 200) {
        // 可以保存到相册或提示用户
        uni.showToast({
          title: '文件下载成功',
          icon: 'success'
        })
      }
    }
  })
  //#endif
}

// 文件预览功能
const previewFile = (url) => {
  const fileName = getFileName(url).toLowerCase()
  
  //#ifdef H5
  // H5环境下直接在新窗口打开预览
  window.open(url, '_blank')
  //#endif
  
  //#ifdef MP-WEIXIN
  // 微信小程序环境下根据文件类型处理
  if (fileName.includes('.pdf') || fileName.includes('.doc') || fileName.includes('.docx') || 
      fileName.includes('.xls') || fileName.includes('.xlsx') || fileName.includes('.ppt') || 
      fileName.includes('.pptx')) {
    // 文档类文件，先下载再预览
    uni.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          uni.openDocument({
            filePath: res.tempFilePath,
            success: function (res) {
              console.log('打开文档成功')
            },
            fail: function (err) {
              console.error('打开文档失败', err)
              uni.showToast({
                title: '无法预览此文件',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: function (err) {
        console.error('下载失败', err)
        uni.showToast({
          title: '预览失败',
          icon: 'none'
        })
      }
    })
  } else if (fileName.includes('.png') || fileName.includes('.jpg') || fileName.includes('.jpeg') || fileName.includes('.gif')) {
    // 图片文件，使用图片预览
    uni.previewImage({
      urls: [url]
    })
  } else {
    // 其他文件在新窗口打开
    window.open(url, '_blank')
  }
  //#endif
}


</script>

<style lang="scss" scoped>
.container-info{
	position: relative;
	width: 100%;
	background-image: url('/static/background.png');
	background-size: 100% 100%;
	background-repeat: no-repeat;
	.title{
		position: relative;
		box-sizing: border-box;
		padding-top: 50rpx;
		padding-left: 20rpx;
		position: relative;
		width: 100%;
		height: 300rpx;
		display: flex;
		.icon{
			width: 40rpx;
			height: 40rpx;
			background-image: url('/static/unitIcon.png');
			background-size: 100% 100%;
			background-repeat: no-repeat;
		}
		.text{
			width: 320rpx;
			height: 40rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 36rpx;
			color: #181818;
			line-height: 36rpx;
			text-align: left;
			font-style: normal;
		}
	}
	.content-info{
		position: relative;
		height: 1400rpx;
		width: 100%;
		background-color: #FFFFFF;
		border-top-right-radius: 25rpx;
		border-top-left-radius: 25rpx;
		.content-title{
			position: relative;
			width: 100%;
			box-sizing: border-box;
			padding: 30rpx 30rpx;
			display: flex;
			.line{
				position: relative;
				box-sizing: border-box;
				margin-right: 10rpx;
				width: 6rpx;
				height: 28rpx;
				background: #468BFB;
				border-radius: 0rpx 4rpx 4rpx 0rpx;
			}
			.title-info{
				position: relative;
				// width: 180rpx;
				height: 28rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 30rpx;
				color: #181818;
				line-height: 28rpx;
				text-align: left;
				font-style: normal;
			}
		}
		.info{
			height: 200rpx;
			position: relative;
			width: 100%;
			box-sizing: border-box;
			padding: 20rpx 20rpx;
			margin: 0;
			display: flex;
			justify-content: center;
			align-items: center;
			.title-info{
				flex: 1;
				text-align: center;
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				color: #6E6D72;
				text-align: center;
				font-style: normal;
			}
			.option{
				flex: 4;
			}
		}
		.error-message {
			color: red;
			font-size: 24rpx;
			padding-left: 180rpx;
			margin-top: -20rpx;
			height: 40rpx;
		}
		.selectOption{
			box-sizing: border-box;
			padding: 10rpx 55rpx;
		}
		.confirm{
			position: relative;
			box-sizing: border-box;
			margin-top: 100rpx;
			width: 686rpx;
			height: 80rpx;
			background: linear-gradient( 180deg, #6FA4FD 0%, #468BFA 100%);
			border-radius: 16rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 80rpx;
			text-align: right;
			font-style: normal;
		}
	}
}
.pop-up-window{
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	.application-history {
	  width: 700rpx;
	  // border-radius: 16rpx;
	  border-bottom-left-radius: 16rpx;
	  border-bottom-right-radius: 16rpx;
	  overflow: hidden;
	  margin-bottom: 15rpx;
	  .table-container {
	    .table-header {
	      display: flex;
	      background-color: #1a73e8;
		  border-top-right-radius: 16rpx;
		  border-top-left-radius: 16rpx;
	      color: #fff;
	      font-weight: bold;
	      flex-shrink: 0;
	      
	      .header-item {
	        flex: 1;
	        padding: 20rpx 0;
	        text-align: center;
	        font-size: 28rpx;
	        white-space: nowrap;
	        overflow: hidden;
	        text-overflow: ellipsis;
	      }
	    }
	    
	    .table-body {
	      max-height: 400rpx;
	      overflow-y: auto;
	      
	      .table-row {
	        display: flex;
	        background-color: #fff;
	        border-bottom: 2rpx solid #f0f0f0;
	        
	        &:last-child {
	          border-bottom: none;
	        }
	        
	        &:nth-child(even) {
	          background-color: #fafafa;
	        }
	        
	        .table-cell {
	          flex: 1;
	          padding: 20rpx;
	          text-align: center;
	          font-size: 23rpx;
	          color: #333;
	          white-space: nowrap;
	          overflow: hidden;
	          text-overflow: ellipsis;
	          
	          &:first-child {
	            font-weight: 500;
	          }
	          
	          &:nth-child(2) {
	            color: #007bff;
	            font-weight: 500;
	          }
			  
			  &:last-child {
			    font-weight: 500;
			  }
			  
	        }
	      }
	    }
	  }
	}
	.applyQuantity{
		margin: 0 auto 20rpx;
		width: 400rpx;
		height: 36rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #888EA6;
		line-height: 36rpx;
		text-align: center;
		font-style: normal;
	}
	.button{
		display: flex;
		.closeStyle{
			margin: 0 auto 40rpx;
			width: 220rpx;
			height: 72rpx;
			background: linear-gradient( 180deg, #6FA4FD 0%, #468BFA 100%);
			border-radius: 16rpx;
		}
		.downloadStyle{
			margin: 0 auto 40rpx;
			width: 220rpx;
			height: 72rpx;
			background: linear-gradient( 180deg, #6FA4FD 0%, #468BFA 100%);
			border-radius: 16rpx;
		}
	}
}
</style>